import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.sql.*;

public class ImageDatabaseExample {

    private static final String URL = "jdbc:mysql://localhost:3306/car";
    private static final String USER = "root";
    private static final String PASSWORD = "4416";
//  存图片
    public static void main(String[] args) {
        try {
            // 加载数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 创建数据库连接
            Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);

            // 准备SQL语句，用于插入图片
            String sql = "update car set picture=? where id=?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            // 设置图片ID
            preparedStatement.setInt(2,1);

            // 读取图片文件
            FileInputStream fis = new FileInputStream("src/picture/1.png");

            // 将图片文件转换为字节数组
            byte[] imageBytes = new byte[(int) fis.available()];
//            fis.read(imageBytes);

            // 设置图片字节数组
            preparedStatement.setBytes(1, imageBytes);

            // 执行插入操作
            preparedStatement.executeUpdate();

            // 关闭资源
            fis.close();
            preparedStatement.close();
            connection.close();

            System.out.println("图片存储成功！");
        } catch (ClassNotFoundException e) {
            System.out.println("未找到数据库驱动：" + e.getMessage());
        } catch (SQLException e) {
            System.out.println("数据库操作出错：" + e.getMessage());
        } catch (IOException e) {
            System.out.println("读取图片文件出错：" + e.getMessage());
        }
    }
    //取图片   select * from car where id=?


//    public static void main(String[] args) throws IOException {
//        JFrame frame = new JFrame();
//        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//        frame.setTitle("Image Database Example");
//        frame.setSize(900, 600);
//        String a="2";
//        BufferedImage image = ImageIO.read(new File("src/picture/"+a+".png"));
//        JPanel panel = new JPanel(){
//            public void paint(Graphics g){
//                g.drawImage(image, 0, 0, null);
//            }
//        };
//        panel.setLayout(null);
//        frame.add(panel);
//        frame.setVisible(true);
//    }
}
